package ru.spb.osll.myfit.server.parser;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;

import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;

import ru.spb.osll.myfit.common.PageElement;
import ru.spb.osll.myfit.common.PageElementType;
import ru.spb.osll.myfit.common.WikiText;
import ru.spb.osll.myfit.server.Converter;
import ru.spb.osll.myfit.util.StringUtils;

public class WikiElementParserText {

  private WikiElementParser wikiParser;
  private Converter converter;

  @Before
  public void setUp() {
    converter = EasyMock.createMock(Converter.class);
    wikiParser = new WikiElementParser(converter);
  }

  @Test
  public void testSimpleWikiText() {
    String wiki = "[[.Text]]";
    String html = "<a href=\".Text\">.Text</a>";
    EasyMock.expect(converter.convertWikiToHtml(wiki)).andReturn(html);
    EasyMock.replay(converter);

    assertTrue(wikiParser.matches(wiki));

    assertNull(wikiParser.parse(wiki));
    PageElement element = wikiParser.reset();

    assertNotNull(element);

    assertTrue(element instanceof WikiText);

    WikiText wikiText = (WikiText) element;
    assertEquals(PageElementType.WIKI_TEXT, wikiText.getType());
    assertEquals(wiki, wikiText.getWikiText());
    assertEquals(html, wikiText.getHtmlText());
    EasyMock.verify(converter);

  }

  @Test
  public void testComplexWikiText() {
    @SuppressWarnings("serial")
    final ArrayList<String> textlines = new ArrayList<String>() {
      {
        add("[[.Text]]");
        add("simpleText");
      }
    };
    
    String html = "<p><a href=\".Text\" title=\".Text\">.Text</a>\nsimpleText</p>";
    String wiki = StringUtils.join(textlines,
        System.getProperty("line.separator"));
    EasyMock.expect(converter.convertWikiToHtml(wiki)).andReturn(html);
    EasyMock.replay(converter);

    for (String line : textlines) {
      wikiParser.parse(line);
    }
    
    PageElement element = wikiParser.reset();

    assertNotNull(element);

    assertTrue(element instanceof WikiText);

    WikiText wikiText = (WikiText) element;
    assertEquals(PageElementType.WIKI_TEXT, wikiText.getType());
    assertEquals(wiki, wikiText.getWikiText());
    assertEquals(html, wikiText.getHtmlText());
    EasyMock.verify(converter);
  }
}
